package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.ReggieContext;
import com.itheima.exception.BizException;
import com.itheima.mapper.*;
import com.itheima.pojo.*;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper  shoppingCartMapper;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public void submit(Orders orders) {
        // 拿到UserId
        Long userId = ReggieContext.get();
        // 拿到地址薄的数据塞刀Orders里
        // 提前生成order的ID
        Long orderId = IdWorker.getId();
        orders.setId(orderId);
        //订单号
        String orderNumber = "RGOD" + IdWorker.getId();
        orders.setNumber(orderNumber);

        //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);  //支付成功

        //下单用户id
        orders.setUserId(userId);

        //下单时间
        orders.setOrderTime(LocalDateTime.now());

        //结账时间
        orders.setCheckoutTime(LocalDateTime.now());

        //实收金额
        AtomicInteger atomicInteger = new AtomicInteger();


        //用户名
        User user = userMapper.selectById(userId);
        if (user==null||user.getStatus()==0){
            throw new BizException("用户不存在或被禁用了");
        }
        orders.setUserName(user.getName());

        //地址
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        if (addressBook==null){
            throw new BizException("地址不存在 无法配送");
        }
        orders.setAddress(addressBook.getDetail());

        //手机号
        orders.setPhone(addressBook.getPhone());

        //收货人
        orders.setConsignee(addressBook.getConsignee());


        //查询对应用户下面的购物车的数据
        List<ShoppingCart> shoppingCartsList = shoppingCartMapper
                .selectList(new LambdaQueryWrapper<ShoppingCart>()
                        .eq(ShoppingCart::getUserId,userId));
        if (shoppingCartsList==null||shoppingCartsList.size()==0){
            throw new BizException("购物车无数据,无法下单");
        }
        // 把购物车数据转换成OrderDetail
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartsList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(orderId);

            atomicInteger.addAndGet(cart.getAmount()
                    .multiply(new BigDecimal(cart.getNumber())
                            .multiply(new BigDecimal("100"))).intValue());

            orderDetailList.add(orderDetail);
        }
        // 最终目标 实现插入一条Orders的记录
        // 再去除以100
        orders.setAmount(new BigDecimal(atomicInteger.get()).divide(new BigDecimal("100"), 2,RoundingMode.HALF_UP));
        this.save(orders);

        // 插入对应的购物车的菜品套餐数据
        this.orderDetailService.saveBatch(orderDetailList);

        // 清空购物车
        this.shoppingCartMapper.delete(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId,userId));

    }

    // 查询订单明细
    @Override
    public Page<Orders> pageOrders(Integer page, Integer pageSize, String number,String beginTime,String endTime ) {

        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        lqw.ge(StringUtils.isNotBlank(beginTime),Orders::getOrderTime,beginTime)
                    .le(StringUtils.isNotBlank(endTime),Orders::getOrderTime,endTime).
                    like(StringUtils.isNotBlank(number),Orders::getNumber,number);
        // 修改时间排序
        lqw.orderByDesc(Orders::getOrderTime);
            return this.page(ordersPage,lqw);
    }


}
